package com.css.fxfzfxqh.zcpt.sys.service.impl;

import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SUserCacheService {
    @Autowired
    SUserService sUserService;
    @Autowired
    RedisTemplate redisTemplate;
    public static final String GET_BY_ID_KEY = "fxqh:suser:";

//    public SUser getSUser(String userId) {
//        if (userId == null) {
//            return null;
//        }
//        ValueOperations<String, SUser> ops = redisTemplate.opsForValue();
//        SUser sUser = ops.get(VALUE_KEY + userId);
//        if (sUser == null) {
//            String sUser1 = sUserService.getSUser(userId);
//            sUser = sUser1;
//        }
//        ops.set(VALUE_KEY + userId, name);
//        redisTemplate.expire(VALUE_KEY + userId, 5L, TimeUnit.MINUTES);
//        return name;
//    }

    /**
     * 获取用户信息
     * <p>
     * 用户id
     * 先走缓存，缓存没有调接口，然后存储缓存，配置缓存60分钟过期
     */
    public SUser getSUser(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        ValueOperations<String, SUser> valueOperations = redisTemplate.opsForValue();
        SUser sUser = valueOperations.get(GET_BY_ID_KEY + userId);
        if (sUser != null) {
            return sUser;
        }
        String userJson = sUserService.getSUser(userId);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
//        if (userJson.contains("")) {
//
//        }
        sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        valueOperations.set(GET_BY_ID_KEY + userId, sUser);
        redisTemplate.expire(GET_BY_ID_KEY + userId, 60, TimeUnit.MINUTES);
        return sUser;
    }
}
